<script lang="ts">
import { getInvitationCode } from './helpers';

export const agreementAccountFromTgStorage = {
  key: 'AGREE_ACCOUNT_FROM_TG',
  isAgreed() {
    return localStorage.getItem(this.key) === '1';
  },
  agree() {
    localStorage.setItem(this.key, '1');
  },
  remove() {
    localStorage.removeItem(this.key);
  },
};

export function createAccount() {
  const ic = getInvitationCode();
  const initData = Telegram.WebApp.initData;
  return apis.apiTelegramCheckUser({ requestBody: { init_data: initData, referral_code: ic } });
}

export const createAccountFromTgPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./CreateAccountFromTg.vue')),
  {
    title: computed(() => $t('g2ZSqGu2e4aAaY1I8lv09')),
    wrapClassName: 'ant-cover__Modal-drawer [--modal-height:fit-content]',
    width: 400,
    centered: true,
    footer: null,
    maskClosable: false,
    async opener(open) {
      if (!envs.isTgApp)
        return;

      const isAuthed = useAuthed();
      await sleep(1000);

      watch(
        () => !isAuthed.value && agreementAccountFromTgStorage.isAgreed(),
        async (auto) => {
          if (auto) {
            await createAccount();
          }
        },
        { immediate: true },
      );

      !isAuthed.value && !agreementAccountFromTgStorage.isAgreed() && open();
    },
  },
);
</script>

<script setup lang="ts">
const emits = defineEmits<{
  close: [];
}>();

const isLoading = ref(false);
const isAgreement = ref(true);

async function onCreate() {
  isLoading.value = true;

  try {
    const res = await createAccount();
  }
  finally {
    isLoading.value = false;
  }

  agreementAccountFromTgStorage.agree();
  emits('close');
}

function onUseOther() {
  globalPopups.sign.open();
  emits('close');
}
</script>

<template>
  <div>
    <I18nT keypath="xVdlQJzoTbZcg3jcMjKpo" tag="div" class="text-sys-text-body">
      <template #name>
        {{ $t('yE0Yic3V28SnWawEsnCvS') }}
      </template>
    </I18nT>

    <div class="divider-h-gradual" />

    <ACheckbox v-model:checked="isAgreement">
      <I18nT keypath="gl747HIsjIgzDDpx1sItB" tag="spab" class="text-sys-text-body">
        <template #link>
          <RouterLink :to="{ name: RN.HELP_PRIVACY_POLICY }">
            <span class="cursor-pointer url-yellow-underline">{{ $t('gaYa7jhqaBxg8ToJwVnn') }}</span>
          </RouterLink>
        </template>
      </I18nT>
    </ACheckbox>

    <AButton
      class="ant-cover__Button-3d-blue mt-3"
      type="primary" block
      :loading="isLoading" :disabled="isLoading || !isAgreement"
      @click="onCreate()"
    >
      <i class="i-ri:telegram-2-fill mr-1 text-1.4em" />
      <span>{{ $t('mJBnC2vx22KZdhgMjF5j') }}</span>
    </AButton>
    <AButton
      class="ant-cover__Button-3d-gray mt-3"
      type="primary" block :disabled="isLoading"
      @click="onUseOther()"
    >
      {{ $t('yE0Yic3V28SnWawEsnCvS') }}
    </AButton>
  </div>
</template>
